package com.jfm.jfmc.core.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfm.jfmc.core.constants.MonitorMetricsSQL;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

@Slf4j
@Configuration
public class DatabaseConfig {

    @Value("${spring.datasource.url}")
    private String dataSourceUrl;

    @Value("${spring.datasource.username}")
    private String dataSourceUsername;

    @Value("${spring.datasource.password}")
    private String dataSourcePassword;

    @Value("${spring.datasource.driver-class-name}")
    private String dataSourceDriverClassName;

    @Value("${spring.datasource.database}")
    private String database;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourceUrl + "/" + database);
        dataSource.setUsername(dataSourceUsername);
        dataSource.setPassword(dataSourcePassword);
        dataSource.setDriverClassName(dataSourceDriverClassName);
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery("SELECT 1");
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/jfm/jfmc/core/mapper/*.xml"));
        return factoryBean.getObject();
    }


    @PostConstruct
    public void initializeDatabase(){
        try {
            // 加载驱动
            Class.forName(dataSourceDriverClassName);

            // 创建临时连接
            Connection connection = DriverManager.getConnection(dataSourceUrl, dataSourceUsername, dataSourcePassword);
            Statement stmt = connection.createStatement();

            // 创建数据库
            String createDbSql = MonitorMetricsSQL.getCreateDbSql(database);
            stmt.execute(createDbSql);

            // 创建超级表
            String createSuperTableSql = MonitorMetricsSQL.getCreateSuperTableSql(database);
            stmt.execute(createSuperTableSql);

            log.info("数据库初始化完成，创建数据库 {}，创建超级表完成 MonitorMetrics", database);

            connection.close();
        } catch (Exception e) {
            log.error("数据库初始化异常,关闭程序", e);
            System.exit(0);
        }
    }

}
